package com.mocai.merchant.spring.resolver;

import com.alibaba.fastjson.JSON;
import com.mocai.merchant.core.domain.ResponseStatus;
import com.mocai.merchant.core.domain.ResponseWrapper;
import com.mocai.merchant.exception.ErrorConstant;
import com.mocai.merchant.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 全局异常处理
 */
public class GlobalHandlerExceptionResolver implements HandlerExceptionResolver {
    private final Logger logger = LoggerFactory.getLogger(GlobalHandlerExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 打印异常信息
        ex.printStackTrace();

        // 响应状态吗
        ResponseStatus responseStatus = new ResponseStatus(ErrorConstant.SYSTEM_001.getCode(), ErrorConstant.SYSTEM_001.getDescription());
        if (ex instanceof ServiceException) {
            ServiceException serviceException = (ServiceException) ex;
            responseStatus.setCode(serviceException.getCode());
            responseStatus.setMessage(serviceException.getDescription());
        }

        // 记录异常日志
        logger.error(JSON.toJSONString(responseStatus), ex);

        // 判断是否是Ajax请求
        if (isAjaxRequest(request)) {
            ResponseWrapper responseWrapper = ResponseWrapper.getInstance();
            responseWrapper.setStatus(responseStatus);
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
                writer.write(JSON.toJSONString(responseWrapper));
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                writer.close();
            }
        }

        // 非Ajax请求
        ModelAndView mav = new ModelAndView();
        mav.addObject("status", responseStatus);
        mav.setViewName("exception/error-500");
        return mav;
    }

    /**
     * 判断是否是ajax请求
     *
     * @param request
     * @return
     */
    static boolean isAjaxRequest(HttpServletRequest request) {
        String ajaxFlag = request.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(ajaxFlag);
    }

}
